package rabbitmq.publisher;

import com.rabbitmq.client.*;
import rabbitmq.constant.Constants;

import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.TimeoutException;

public class PublisherConfirms {
    public static final Integer MESSAGE_COUNT = 200;

    public static Connection createConnection() throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(Constants.HOST);
        factory.setPort(Constants.PORT);
        factory.setUsername(Constants.USER_NAME);
        factory.setPassword(Constants.PASSWORD);
        factory.setVirtualHost(Constants.VIRTUAL);

        Connection connection = factory.newConnection();
        return connection;
    }
    public static void main(String[] args) throws Exception {
        // 单独确认
        publishingMessagesIndividually();
        // 批量确认
        publishingMessagesInBatches();
        // 异步确认
        handlingPublisherConfirmsAsynchronously();
    }
    /**
     * 异步确认
     */
    private static void handlingPublisherConfirmsAsynchronously() throws Exception{
        try(Connection connection = createConnection()) {
            Channel channel = connection.createChannel();
            channel.confirmSelect();
            //
            SortedSet<Long> confirmSet = Collections.synchronizedSortedSet(new TreeSet<>());
            channel.addConfirmListener(new ConfirmListener() {
                @Override
                public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                    if(multiple) {
                        confirmSet.headSet(deliveryTag + 1).clear();
                    }else {
                        confirmSet.remove(deliveryTag);
                    }
                }

                @Override
                public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                    if(multiple) {
                        confirmSet.headSet(deliveryTag + 1).clear();
                    }else {
                        confirmSet.remove(deliveryTag);
                    }
                    // 如果处理失败, 这⾥需要添加处理消息重发的场景. 此处代码省略
                }
            });
            Long start = System.currentTimeMillis();
            for(int i = 0; i < MESSAGE_COUNT; i++) {
                String body = "发送消息： " + i;
                // 发送消息
                channel.basicPublish("", Constants.PUBLISHER_CONFIRMS_QUEUE_NAME1,null,body.getBytes());
            }


            Long end = System.currentTimeMillis();
            System.out.println("异步确认,发送消息： " + MESSAGE_COUNT + "条, 共耗时： " + (end - start) + "ms");
        }
    }

    /**
     * 批量确认
     */
    private static void publishingMessagesInBatches() throws Exception{
        try(Connection connection = createConnection()) {
            Channel channel = connection.createChannel();
            // 开启确认模式
            channel.confirmSelect();
            channel.queueDeclare(Constants.PUBLISHER_CONFIRMS_QUEUE_NAME1, true, false, true, null);

            int bathSize = 200;
            int outstandingMessageCount = 0;


            Long begin = System.currentTimeMillis();
            for(int i = 0; i < MESSAGE_COUNT; i++) {
                String body = "发送消息： " + i;
                // 发送消息
                channel.basicPublish("", Constants.PUBLISHER_CONFIRMS_QUEUE_NAME1,null,body.getBytes());
                outstandingMessageCount++;
                if(bathSize == outstandingMessageCount)  {
                    channel.waitForConfirms(5000);
                    outstandingMessageCount = 0;
                }
            }
            if(outstandingMessageCount > 0) {
                channel.waitForConfirms(5000);
            }
            Long end = System.currentTimeMillis();
            System.out.println("批量确认,发送消息： " + MESSAGE_COUNT + "条, 共耗时： " + (end - begin) + "ms");
        }
    }

    /**
     * 单独确认
     */
    private static void publishingMessagesIndividually() throws Exception {
        try(Connection connection = createConnection()) {
            Channel channel = connection.createChannel();
            // 开启信道确认模式
            channel.confirmSelect();
            channel.queueDeclare(Constants.PUBLISHER_CONFIRMS_QUEUE_NAME1, true, false, true, null);
            Long begin = System.currentTimeMillis();
            for(int i = 0; i < MESSAGE_COUNT; i++) {
                String body = "发送消息： " + i;
                // 发送消息
                channel.basicPublish("", Constants.PUBLISHER_CONFIRMS_QUEUE_NAME1,null,body.getBytes());
                channel.waitForConfirms(5000);
            }
            Long end = System.currentTimeMillis();
            System.out.println("单独确认,发送消息： " + MESSAGE_COUNT + "条, 共耗时： " + (end - begin) + "ms");
        }
    }
}
